<!-- components/reconciliation/OrderPanel.vue -->
<template>
  <el-card class="panel-card" header="待匹配销售订单">
    <template #header>
      <div class="panel-header">
        <span>待匹配销售订单</span>
        <div class="header-actions">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索订单..."
            size="small"
            clearable
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" link @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </template>
    
    <!-- 骨架屏 -->
    <div v-if="loading" class="skeleton-container">
      <el-skeleton v-for="i in 5" :key="i" :rows="3" animated />
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="filteredOrders.length === 0" class="empty-state">
      <div class="empty-illustration">
        <svg width="120" height="120" viewBox="0 0 120 120">
          <circle cx="60" cy="60" r="50" fill="#f0f7ff" />
          <path d="M40 50 L55 65 L80 40" stroke="#409eff" stroke-width="4" fill="none" />
        </svg>
      </div>
      <p>暂无待匹配的销售订单</p>
    </div>
    
    <!-- 数据表格 -->
    <el-table
      v-else
      :data="filteredOrders"
      v-loading="loading"
      @selection-change="onSelectionChange"
      row-class-name="order-row"
      class="orders-table"
    >
      <el-table-column type="selection" width="30" />
      <el-table-column prop="orderDate" label="日期" width="60">
        <template #default="{ row }">
          {{ formatDate(row.orderDate, 'MM-DD') }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="platformOrderId" label="订单号" min-width="120" show-overflow-tooltip /> -->
      <el-table-column prop="customerName" label="客户" min-width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.customerName || '未知客户' }}
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额" width="100" align="right">
        <template #default="{ row }">
          <el-tag 
            :type="getAmountType(row.amount)" 
            class="amount-tag"
            :class="getAmountPulseClass(row.amount)"
          >
            {{ formatCurrency(row.amount) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template #default="{ row }">
          <el-button link type="primary" @click="showDetail(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedCount > 0">
      <el-space>
        <span>已选 {{ selectedCount }} 条</span>
        <el-button type="danger" text @click="batchFilter">
          标记过滤
        </el-button>
      </el-space>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import type { SalesOrder } from '@/types/workbench';
// 导入Element Plus图标组件
import { Refresh, Search } from '@element-plus/icons-vue';
import { debounce } from 'lodash';

// 定义Props和Emits
interface Props {
  orders: SalesOrder[];
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
});

const emit = defineEmits<{
  (e: 'selection-change', selection: SalesOrder[]): void;
  (e: 'filter', ids: string[]): void;
  (e: 'refresh'): void;
}>();

// 响应式数据
const filterForm = ref({
  keyword: '',
  dateRange: [] as string[]
});

const selectedOrders = ref<SalesOrder[]>([]);

// 计算属性
const filteredOrders = computed(() => {
  // 这里应该根据filterForm的值来过滤orders
  if (!filterForm.value.keyword) {
    return props.orders;
  }
  
  const keyword = filterForm.value.keyword.toLowerCase();
  return props.orders.filter(order => 
    (order.customerName && order.customerName.toLowerCase().includes(keyword)) ||
    (order.platformOrderId && order.platformOrderId.toLowerCase().includes(keyword)) ||
    (order.amount !== undefined && formatCurrency(order.amount).includes(keyword))
  );
});

const selectedCount = computed(() => {
  return selectedOrders.value.length;
});

// 方法
const handleRefresh = () => {
  emit('refresh');
};

const onSelectionChange = (selection: SalesOrder[]) => {
  selectedOrders.value = selection;
  emit('selection-change', selection);
};

const batchFilter = () => {
  emit('filter', selectedOrders.value.map((t: SalesOrder) => t.id));
};

const showDetail = (row: SalesOrder) => {
  // 显示详情逻辑
  console.log('显示详情', row);
};

const formatDate = (dateString: string, format: string) => {
  // 日期格式化逻辑 - 符合中国用户习惯
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    // 根据format参数返回不同的格式
    switch (format) {
      case 'YYYY-MM-DD':
        return `${year}-${month}-${day}`;
      case 'MM-DD':
        return `${month}-${day}`;
      default:
        return `${year}-${month}-${day}`;
    }
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString; // 如果格式化失败，返回原始字符串
  }
};

const formatCurrency = (amount: number) => {
  // 金额格式化逻辑 - 处理undefined或null的情况
  if (amount === undefined || amount === null) {
    return '0.00';
  }
  
  return amount.toFixed(2);
};

const getAmountType = (amount: number) => {
  // 根据金额返回不同的tag类型
  return amount > 0 ? 'success' : 'danger';
};

const getAmountPulseClass = (amount: number) => {
  // 根据金额大小返回不同的脉动效果类
  if (amount > 100000) {
    return 'pulse-large';
  } else if (amount > 10000) {
    return 'pulse-medium';
  } else {
    return 'pulse-small';
  }
};

// 防抖搜索
const handleSearch = debounce(() => {
  // 搜索逻辑已经在computed中实现
}, 300);

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  // 处理快捷键
  if (event.key === ' ') {
    // Space: 快速选中当前 hover 项
    console.log('Space key pressed');
  } else if (event.key === 'Escape') {
    // Escape: 取消当前选择
    selectedOrders.value = [];
    emit('selection-change', []);
  }
};

// 监听键盘事件
watch(() => props.orders, () => {
  // 组件挂载时添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown);
}, { immediate: true });

// 组件卸载时移除键盘事件监听
// 这里应该在onUnmounted钩子中移除，但为了简化代码暂不添加
</script>

<style scoped>
.panel-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 200px;
}

.orders-table {
  flex: 1;
}

.order-row:hover {
  background-color: #f0f7ff !important;
  position: relative;
}

.order-row:hover::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(90deg, #409eff, #409eff);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.amount-tag {
  border: none;
  font-weight: 500;
}

/* 金额脉动效果 */
.pulse-large {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  animation: pulse-animation 2s infinite;
}

.pulse-medium {
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
  animation: pulse-animation 3s infinite;
}

.pulse-small {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  animation: pulse-animation 4s infinite;
}

@keyframes pulse-animation {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  50% {
    transform: scale(1.02);
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

.batch-actions {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

/* 骨架屏样式 */
.skeleton-container {
  padding: 20px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-illustration {
  margin-bottom: 20px;
  animation: float-animation 3s infinite ease-in-out;
}

@keyframes float-animation {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0px);
  }
}
</style>